package csrc

import (
	"gitee.com/gcom/gbox/errors"
	"gitee.com/gcom/stockdock/core/support"
	"github.com/jinzhu/gorm"
)

type StockEntity struct {
	support.SimpleEntity
	*Stock
}

func (StockEntity) TableName() string {
	return "stock"
}

func UpdateStockList(db *gorm.DB, entities []*StockEntity) (int64, error) {
	return support.BatchInsertOrUpdate(db, entities, true)
}

func GetStockList(db *gorm.DB, q *StockListQuery) (result []*StockEntity, err error) {
	var sql = "1=1"
	var cond = []interface{}{""}
	if q.Name != "" {
		sql += " and name like ?"
		cond = append(cond, "%"+q.Name+"%")
	}
	if q.Code != "" {
		sql += " and code like ?"
		cond = append(cond, "%"+q.Code+"%")
	}
	cond[0] = sql
	err = db.Model(StockEntity{}).Limit(q.Ps).Offset(q.Pn*q.Ps).Find(&result, cond...).Error
	return result, err
}

func GetStockAll(db *gorm.DB) (result []struct {
	Code string
	Name string
}, err error) {
	err = db.Model(StockEntity{Stock: &Stock{}}).Select("code, name").Scan(&result).Error
	if err != nil {
		err = errors.Wrap(err, "查询全部股票失败")
	}
	return result, err
}
